package org.tangerinejunction.imstats.logs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Calendar;

import org.tangerinejunction.imstats.data.Account;

/**
 * A LogFile represents one instant messaging log file.
 * It is associated with an Account and a date.
 * Note: This assumes that log files do not span multiple days.
 * 
 * @author meganthorsen
 */
public class LogFile extends File 
{
	private static final long serialVersionUID = 4507195897655769383L;
	
	private Account account;
	private Calendar date;
	private boolean isStartedByMe;
	
	/**
	 * 
	 * @param file		the basic File object
	 * @param account	the Account with which this LogFile is associated
	 * @param date		the Calendar date contained in this LogFile
	 */
	public LogFile(File file, Account account, Calendar date) 
	{
		super(file.getAbsolutePath());
		this.account = account;
		this.date = date;
        this.isStartedByMe = true;
        try 
        {
            BufferedReader input = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = input.readLine()) != null)
            {
                if (line.startsWith("<message sender=\""))
                {
                    int closingQuoteIndex = line.indexOf("\"", 17);
                    String sender = line.substring(17, closingQuoteIndex);
                    if (!sender.equals(account.get(Account.MY_ACCOUNT_NAME_KEY)))
                        isStartedByMe = false;
                    break;
                }
            }
            input.close();
        } 
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
		account.addLogFile(this);
	}

	/**
	 * 
	 * @return	the Account associated with this LogFile
	 */
	public Account getAccount()
	{
		return account;
	}
	
	/**
	 * 
	 * @return	the Calendar date associated with this LogFile
	 */
	public Calendar getDate()
	{
		return date;
	}
	
	public boolean isStartedByMe()
	{
	    return isStartedByMe;
	}
}
